﻿using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Transactions;
using NPMonitor.DataModel;
using NPMonitor.Implementation.Internal;
using NPMonitor.Interfaces;

namespace NPMonitor.Implementation.Store
{
    public class NotificationStore : INotificationStore
    {
        /// <summary>
        /// 根据用户Id，获取当前用户所有的Notification
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public IEnumerable<NotificationData> GetAllNotificationsByUserId(int userId)
        {
            using (var ctx = new DbStoreContext())
            {
                return ctx.Notifications.Where(p => p.UserId == userId).ToList();
            }
        }

        /// <summary>
        /// 更新用户的Setting信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="form"></param>
        public void UpdateNotificationsByUserId(int userId, NameValueCollection form)
        {
            using (var ts = new TransactionScope())
            {
                using (var ctx = new DbStoreContext())
                {
                    List<int> deleteIds = ctx.Notifications.Where(p => p.UserId == userId).Select(p => p.Id).ToList();
                    if (deleteIds.Count > 0)
                    {
                        foreach (int id in deleteIds)
                        {
                            NotificationData info = ctx.Notifications.FirstOrDefault(p => p.Id == id);
                            ctx.Notifications.Remove(info);
                        }
                    }

                    // key should be something like @"aaa$bbb"
                    foreach (string key in form.Keys)
                    {
                        if (!key.Contains('$')) continue;

                        string[] param = key.Split('$');
                        if (param.Length != 2) continue;

                        int jobId = 0;
                        if (!int.TryParse(param[0], out jobId)) continue;

                        string strEvent = param[1];

                        ctx.Notifications.Add(new NotificationData
                        {
                            UserId = userId,
                            TaskId = jobId,
                            Event = strEvent
                        });
                    }

                    ctx.SaveChanges();
                    ts.Complete();
                }
            }
        }

    }
}
